'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	const {
		userId,
		articleId
	} = event;
	//找到用户的点赞数组
	const userList = await db.collection('user').doc(userId).get()
	const thumbs_up_article_ids = userList.data[0].thumbs_up_article_ids;
	let tempArr = null;
	let returnMsg = '';
	let thumbCount = 0;
	//判断是否在数组中
	if (thumbs_up_article_ids.includes(articleId)) {
		//删除
		tempArr = dbCmd.pull(articleId);
		returnMsg = '取消点赞成功';
		thumbCount = -1;

	} else {
		tempArr = dbCmd.addToSet(articleId);
		returnMsg = '点赞成功';
		thumbCount = 1
	};
	//更新云端数据
	await db.collection('user').doc(userId).update({
		thumbs_up_article_ids: tempArr
	});
	await db.collection('article').doc(articleId).update({
		thumbs_up_count: dbCmd.inc(thumbCount)
	})
	return {
		code: 0,
		data: {
			returnMsg
		}
	}
};